# -*- coding: utf-8 -*-

from core.serializers import CustomModelSerializer
from rest_framework import serializers, status
from apps.sys.models import Menu


class RouterMetaSerializer(CustomModelSerializer):
    """
    子路由-序列化器
    """
    title = serializers.CharField(source="name")

    class Meta:
        model = Menu
        fields = ['icon', 'link', 'cache', 'title']


class RouterSerializer(CustomModelSerializer):
    """
    前端菜单路由的简单序列化器
    """
    children = serializers.SerializerMethodField(read_only=True)
    meta = serializers.SerializerMethodField(read_only=True)
    hidden = serializers.BooleanField(source="visible")

    def get_children(self, instance):
        user = self.request.user
        allocated_menus = Menu.objects.all()
        if not user.is_superuser:
            menu_ids = user.roles.values_list('menu__id', flat=True)
            allocated_menus = Menu.objects.filter(id__in=menu_ids, status=0)
        queryset = allocated_menus.filter(
            parent=instance.id, type__in=['M', 'C'])
        if (queryset):
            return RouterSerializer(queryset, many=True, request=self.request).data
        else:
            return None

    def get_meta(self, instance):
        queryset = Menu.objects.filter(id=instance.id)
        if (queryset):
            return RouterMetaSerializer(queryset, many=True, request=self.request).data[0]
        else:
            return None

    def to_representation(self, instance):
        data = super().to_representation(instance)
        if (data['children'] == None):
            del data['children']
            del data['nesting']
            del data['redirect']
        return data

    class Meta:
        model = Menu
        fields = ['id', 'parent', 'children', 'meta', 'component',
                  'hidden', 'name', 'path', 'nesting', 'redirect']
        read_only_fields = ["id"]
